import Exif from 'exif-js'
import axios from '@/common/axios-td.js'//请求模块
import config from '@/config.js'

function imgPreview(_options) {
    let Orientation;
    //去获取拍照时的信息，解决拍出来的照片旋转问题
    Exif.getData(_options.file, function () {
        Orientation = Exif.getTag(this, 'Orientation');//获取旋转角度
        _options.result=_options.result|| 'base64';
        if(_options.base64.length<=0) {
            //转为base64
        }

        CompressAndRotate({
            base64:_options.base64,
            dir:Orientation,
            size:_options.size || 3,//压缩大小  M
            pixel:_options.pixel || 3000,//图片 宽度 超过x 等比例压缩
            level:_options.level || 1,//压缩等级
            success:(_res)=>{
                if(_options.result=='base64') {
                    typeof _options.success==="function" && _options.success(_res);
                    return;
                }
                //转为流
                var file=convertBase64UrlToFile(_res,Math.ceil(Math.random() * 100000) + ".jpg")
                typeof _options.success==="function" && _options.success(file);
                return;
            }
        })

    })
}
function CompressAndRotate(_options) {
    if(_options.base64.length<=(_options.size*1014*1024)) {
        typeof _options.success==="function" && _options.success(_options.base64);
        return;
    }
    var image = new Image();
    image.onload = function () {
        var degree = 0, drawWidth, drawHeight, width, height;
        drawWidth = this.naturalWidth;
        drawHeight = this.naturalHeight;
        //以下改变一下图片大小
        var maxSide = Math.max(drawWidth, drawHeight);
        if (maxSide > _options.pixel) {
            var minSide = Math.min(drawWidth, drawHeight);
            minSide = minSide / maxSide * _options.pixel;
            maxSide = _options.pixel;
            if (drawWidth > drawHeight) {
                drawWidth = maxSide;
                drawHeight = minSide;
            } else {
                drawWidth = minSide;
                drawHeight = maxSide;
            }
        }
        var canvas = document.createElement('canvas');
        canvas.width = width = drawWidth;
        canvas.height = height = drawHeight;
        var context = canvas.getContext('2d');
        //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
        switch (_options.dir) {
            //iphone横屏拍摄，此时home键在左侧
            case 3:
                degree = 180;
                drawWidth = -width;
                drawHeight = -height;
                break;
            //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
            case 6:
                canvas.width = height;
                canvas.height = width;
                degree = 90;
                drawWidth = width;
                drawHeight = -height;
                break;
            //iphone竖屏拍摄，此时home键在上方
            case 8:
                canvas.width = height;
                canvas.height = width;
                degree = 270;
                drawWidth = -width;
                drawHeight = height;
                break;
        }
        //使用canvas旋转校正
        context.rotate(degree * Math.PI / 180);
        context.drawImage(this, 0, 0, drawWidth, drawHeight);
        //返回校正图片base6
        typeof _options.success==="function" && _options.success(canvas.toDataURL(_options.base64.split(';')[0].replace('data:', ''),_options.level));
    }
    image.src = _options.base64;
}//压缩盘和旋转
//base64 to file
function convertBase64UrlToFile(urlData, filename) {
    var arr = urlData.split(',');
    var bytes = window.atob(arr[1]);        //去掉url的头，并转换为byte  
    var mime = arr[0].match(/:(.*?);/)[1];// 结果：   image/png
    //处理异常,将ascii码小于0的转换为大于0  
    var u8arr = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(u8arr);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new File([u8arr], filename, { type: mime });
}

function UserUpLoad(_options){
    var token=window.localStorage.getItem('usertoken') || '';
    if(token.length<=0) {
        return;
    }

    typeof _options.before==="function" && _options.before()

    imgPreview({
        result:'file',//返回格式 base64或file
        file:_options.file.file,//文件
        base64:_options.file.content,//base64
        size:1,//压缩大小  M
        pixel:1000,//图片 宽度 超过x 等比例压缩
        level:0.5,//压缩等级
        success:(_res)=>{
            var api = config.url[config.url.mode].img_url + "/tools/upload_ajax.ashx?action=UpLoadUserFile";
            var data = new FormData();
            data.append('Filedata',_res)
            data.append('token',token)

            axios.posthttp({
                headers:{
                    'Content-Type':'application/x-www-form-urlencoded'
                },
                url:api,
                data:data,
                success:(_res,_msg)=>{
                    if(_res.status!=200) {
                        typeof _options.error==="function" && _options.error('上传请求异常')
                        return;
                    }
                    var data=_res.data
                    if(!data) {
                        typeof _options.error==="function" && _options.error('上传失败，返回数据为空，请稍后尝试!')
                        return;
                    }
                    if(data.path==null || data.path==undefined || data.path=='undefined' || data.path.length<=0) {
                        typeof _options.error==="function" && _options.error('上传失败，获取路径失败，请稍后尝试!')
                        return;
                    }

                    typeof _options.success==="function" && _options.success(data.path)
                },
                error:(_msg)=>{
                    typeof _options.error==="function" && _options.error(_msg)
                }
            })
        }
    })
}

export default {
    imgPreview:imgPreview,//处理图片压缩和旋转
    convertBase64UrlToFile:convertBase64UrlToFile,//base64转file
    UserUpLoad:UserUpLoad
}